// ===== 音乐播放器功能 =====

class MusicPlayer {
    constructor() {
        this.audio = null;
        this.playBtn = null;
        this.isPlaying = false;
        this.volume = 0.5;
        this.isInitialized = false;

        this.init();
    }

    init() {
        // 等待DOM加载完成
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => this.setupPlayer());
        } else {
            this.setupPlayer();
        }
    }

    setupPlayer() {
        this.audio = document.getElementById('bgMusic');
        this.playBtn = document.getElementById('playBtn');

        if (!this.audio || !this.playBtn) {
            console.warn('音乐播放器元素未找到');
            return;
        }

        // 设置初始音量
        this.audio.volume = this.volume;

        // 绑定事件
        this.bindEvents();

        // 尝试预加载音频
        this.preloadAudio();

        this.isInitialized = true;
        console.log('音乐播放器初始化完成');
    }

    bindEvents() {
        // 播放按钮点击事件
        this.playBtn.addEventListener('click', () => {
            this.togglePlay();
        });

        // 音频事件
        this.audio.addEventListener('loadstart', () => {
            this.updatePlayButton('loading');
        });

        this.audio.addEventListener('canplay', () => {
            this.updatePlayButton('ready');
        });

        this.audio.addEventListener('play', () => {
            this.isPlaying = true;
            this.updatePlayButton('playing');
            this.addFloatingNotes();
        });

        this.audio.addEventListener('pause', () => {
            this.isPlaying = false;
            this.updatePlayButton('paused');
        });

        this.audio.addEventListener('ended', () => {
            this.isPlaying = false;
            this.updatePlayButton('ended');
            this.showSongComplete();
        });

        this.audio.addEventListener('error', (e) => {
            console.error('音频加载错误:', e);
            this.updatePlayButton('error');
            this.showError();
        });

        // 键盘快捷键
        document.addEventListener('keydown', (e) => {
            if (e.code === 'Space' && e.target.tagName !== 'INPUT') {
                e.preventDefault();
                this.togglePlay();
            }
        });

        // 页面可见性变化处理
        document.addEventListener('visibilitychange', () => {
            if (document.hidden && this.isPlaying) {
                this.pause();
            }
        });
    }

    async preloadAudio() {
        try {
            // 尝试加载音频
            await this.audio.load();
        } catch (error) {
            console.error('音频预加载失败:', error);
        }
    }

    togglePlay() {
        if (!this.isInitialized) {
            console.warn('音乐播放器未初始化');
            return;
        }

        if (this.isPlaying) {
            this.pause();
        } else {
            this.play();
        }
    }

    async play() {
        try {
            // 现代浏览器需要用户交互才能播放音频
            await this.audio.play();
            console.log('开始播放: Beautiful In White');
        } catch (error) {
            if (error.name === 'NotAllowedError') {
                this.showPlayPrompt();
            } else {
                console.error('播放失败:', error);
                this.showError();
            }
        }
    }

    pause() {
        this.audio.pause();
        console.log('音乐已暂停');
    }

    setVolume(newVolume) {
        this.volume = Math.max(0, Math.min(1, newVolume));
        this.audio.volume = this.volume;
    }

    updatePlayButton(state) {
        if (!this.playBtn) return;

        // 移除所有状态类
        this.playBtn.classList.remove('playing', 'loading', 'error');

        switch (state) {
            case 'playing':
                this.playBtn.classList.add('playing');
                this.playBtn.innerHTML = `
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
                        <rect x="6" y="4" width="4" height="16"/>
                        <rect x="14" y="4" width="4" height="16"/>
                    </svg>
                `;
                break;
            case 'loading':
                this.playBtn.innerHTML = `
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
                        <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2" fill="none" stroke-dasharray="31.4" stroke-dashoffset="31.4" style="animation: spin 1s linear infinite"/>
                        <style>
                            @keyframes spin { to { stroke-dashoffset: 0; } }
                        </style>
                    </svg>
                `;
                break;
            case 'error':
                this.playBtn.classList.add('error');
                this.playBtn.innerHTML = `
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
                        <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z"/>
                    </svg>
                `;
                break;
            default:
                this.playBtn.innerHTML = `
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
                        <path d="M8 5v14l11-7z"/>
                    </svg>
                `;
        }
    }

    showPlayPrompt() {
        // 创建用户友好的播放提示
        const prompt = document.createElement('div');
        prompt.className = 'music-prompt';
        prompt.innerHTML = `
            <div class="prompt-content">
                <p>🎵 想要听《Beautiful In White》吗？</p>
                <p>点击播放按钮开始播放</p>
                <button class="prompt-confirm">好的</button>
            </div>
        `;
        prompt.style.cssText = `
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(248, 244, 230, 0.95);
            padding: 2rem;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            z-index: 10000;
            text-align: center;
            backdrop-filter: blur(10px);
            border: 1px solid var(--accent-color);
        `;

        const style = document.createElement('style');
        style.textContent = `
            .music-prompt .prompt-content p {
                margin-bottom: 1rem;
                color: var(--text-color);
            }
            .music-prompt .prompt-confirm {
                background: var(--accent-color);
                color: white;
                border: none;
                padding: 0.8rem 2rem;
                border-radius: 25px;
                cursor: pointer;
                font-size: 1rem;
                transition: all 0.3s ease;
            }
            .music-prompt .prompt-confirm:hover {
                background: var(--emphasis-color);
                transform: scale(1.05);
            }
        `;
        document.head.appendChild(style);

        document.body.appendChild(prompt);

        // 自动移除提示
        prompt.querySelector('.prompt-confirm').addEventListener('click', () => {
            prompt.remove();
        });

        setTimeout(() => {
            if (prompt.parentNode) {
                prompt.remove();
            }
        }, 5000);
    }

    showError() {
        const errorMsg = document.createElement('div');
        errorMsg.className = 'music-error';
        errorMsg.textContent = '音乐文件加载失败，请检查网络连接';
        errorMsg.style.cssText = `
            position: fixed;
            bottom: 20px;
            left: 50%;
            transform: translateX(-50%);
            background: rgba(198, 40, 40, 0.9);
            color: white;
            padding: 1rem 2rem;
            border-radius: 10px;
            z-index: 10000;
            opacity: 0;
            transition: opacity 0.3s ease;
        `;

        document.body.appendChild(errorMsg);

        // 显示错误消息
        setTimeout(() => {
            errorMsg.style.opacity = '1';
        }, 100);

        // 自动隐藏
        setTimeout(() => {
            errorMsg.style.opacity = '0';
            setTimeout(() => errorMsg.remove(), 300);
        }, 3000);
    }

    showSongComplete() {
        const completeMsg = document.createElement('div');
        completeMsg.className = 'song-complete';
        completeMsg.innerHTML = `
            <div class="complete-content">
                <p>🎵 歌曲播放完毕</p>
                <p>希望你喜欢这首《Beautiful In White》</p>
            </div>
        `;
        completeMsg.style.cssText = `
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: linear-gradient(135deg, rgba(212, 175, 55, 0.9), rgba(255, 224, 130, 0.9));
            color: white;
            padding: 2rem;
            border-radius: 20px;
            z-index: 10000;
            text-align: center;
            box-shadow: 0 10px 30px rgba(212, 175, 55, 0.3);
            animation: songCompleteAnimation 0.5s ease;
        `;

        const style = document.createElement('style');
        style.textContent = `
            @keyframes songCompleteAnimation {
                0% {
                    opacity: 0;
                    transform: translate(-50%, -50%) scale(0.8);
                }
                100% {
                    opacity: 1;
                    transform: translate(-50%, -50%) scale(1);
                }
            }
            .complete-content p {
                margin: 0.5rem 0;
                font-size: 1.1rem;
            }
        `;
        document.head.appendChild(style);

        document.body.appendChild(completeMsg);

        setTimeout(() => {
            completeMsg.style.opacity = '0';
            setTimeout(() => completeMsg.remove(), 500);
        }, 4000);
    }

    addFloatingNotes() {
        // 播放时添加音符飘落效果
        if (!this.isPlaying) return;

        const note = document.createElement('div');
        note.innerHTML = ['♪', '♫', '♬', '♩'][Math.floor(Math.random() * 4)];
        note.style.cssText = `
            position: fixed;
            left: ${Math.random() * window.innerWidth}px;
            top: ${window.innerHeight + 20}px;
            font-size: ${Math.random() * 1.5 + 1}rem;
            color: var(--accent-color);
            opacity: 0.7;
            pointer-events: none;
            z-index: 1000;
            animation: floatNote ${Math.random() * 3 + 5}s linear;
        `;

        // 添加音符飘落动画
        if (!document.querySelector('#noteAnimationStyle')) {
            const noteStyle = document.createElement('style');
            noteStyle.id = 'noteAnimationStyle';
            noteStyle.textContent = `
                @keyframes floatNote {
                    0% {
                        transform: translateY(0) rotate(0deg);
                        opacity: 0;
                    }
                    10% {
                        opacity: 0.7;
                    }
                    90% {
                        opacity: 0.7;
                    }
                    100% {
                        transform: translateY(-${window.innerHeight + 100}px) rotate(360deg);
                        opacity: 0;
                    }
                }
            `;
            document.head.appendChild(noteStyle);
        }

        document.body.appendChild(note);

        // 移除音符
        setTimeout(() => {
            note.remove();
        }, 8000);
    }
}

// 音频可视化效果
class AudioVisualizer {
    constructor(audioElement) {
        this.audio = audioElement;
        this.canvas = null;
        this.ctx = null;
        this.analyser = null;
        this.dataArray = null;
        this.animationId = null;

        this.init();
    }

    init() {
        if (!this.audio) return;

        // 创建canvas元素
        this.canvas = document.createElement('canvas');
        this.canvas.id = 'audioVisualizer';
        this.canvas.style.cssText = `
            position: fixed;
            bottom: 100px;
            left: 50%;
            transform: translateX(-50%);
            width: 300px;
            height: 60px;
            z-index: 999;
            pointer-events: none;
            opacity: 0.3;
        `;

        document.body.appendChild(this.canvas);
        this.ctx = this.canvas.getContext('2d');

        // 设置Web Audio API
        this.setupAudioContext();

        // 监听播放状态
        this.audio.addEventListener('play', () => this.start());
        this.audio.addEventListener('pause', () => this.stop());
    }

    setupAudioContext() {
        try {
            const audioContext = new (window.AudioContext || window.webkitAudioContext)();
            this.analyser = audioContext.createAnalyser();
            this.analyser.fftSize = 64;

            const source = audioContext.createMediaElementSource(this.audio);
            source.connect(this.analyser);
            this.analyser.connect(audioContext.destination);

            const bufferLength = this.analyser.frequencyBinCount;
            this.dataArray = new Uint8Array(bufferLength);
        } catch (error) {
            console.warn('音频可视化初始化失败:', error);
        }
    }

    start() {
        if (!this.analyser) return;
        this.draw();
    }

    stop() {
        if (this.animationId) {
            cancelAnimationFrame(this.animationId);
            this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        }
    }

    draw() {
        this.animationId = requestAnimationFrame(() => this.draw());

        this.analyser.getByteFrequencyData(this.dataArray);

        this.ctx.fillStyle = 'rgba(248, 244, 230, 0.2)';
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);

        const barWidth = (this.canvas.width / this.dataArray.length) * 2.5;
        let barHeight;
        let x = 0;

        for (let i = 0; i < this.dataArray.length; i++) {
            barHeight = (this.dataArray[i] / 255) * this.canvas.height * 0.8;

            // 渐变色条
            const gradient = this.ctx.createLinearGradient(0, this.canvas.height, 0, 0);
            gradient.addColorStop(0, '#D4AF37');
            gradient.addColorStop(0.5, '#FFE082');
            gradient.addColorStop(1, '#C62828');

            this.ctx.fillStyle = gradient;
            this.ctx.fillRect(x, this.canvas.height - barHeight, barWidth, barHeight);

            x += barWidth + 1;
        }
    }
}

// 初始化音乐播放器
let musicPlayer;
let audioVisualizer;

document.addEventListener('DOMContentLoaded', function() {
    musicPlayer = new MusicPlayer();

    // 延迟初始化可视化效果，避免阻塞页面加载
    setTimeout(() => {
        const audioElement = document.getElementById('bgMusic');
        if (audioElement) {
            audioVisualizer = new AudioVisualizer(audioElement);
        }
    }, 2000);
});

// 导出供全局使用
window.MusicPlayer = MusicPlayer;
window.AudioVisualizer = AudioVisualizer;
window.musicPlayer = musicPlayer;